<template>
  <div class="app-container">
    <el-form label-width="120px"  >
      <el-form-item label="课程名称：" style="width: 300px">
        <el-input v-model="privateCoursesAddVo.courses.name"/>
      </el-form-item>
      <el-form-item label="课程图片：">
        <el-upload
          name="file"
          class="avatar-uploader"
          action="http://localhost:8080/upload/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img  v-if="privateCoursesAddVo.courses.img" :src="'http://rj0387v46.hn-bkt.clouddn.com/'+privateCoursesAddVo.courses.img" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item >
      <el-form-item label="课程时长：" style="width: 300px">
        <el-input v-model="privateCoursesAddVo.courses.timeLength"/>
      </el-form-item>
      <el-form-item label="每日课程上限：" style="width: 300px">
        <el-input v-model="privateCoursesAddVo.courses.upperLimit"/>
      </el-form-item>
      <el-form-item label="教练：" style="width: 300px">
        <el-select v-model="privateCoursesAddVo.courses.coachId"  placeholder="请选择教练">
          <el-option
            v-for="coach in coachVo"
            :key="coach.id"
            :label="coach.name"
            :value="coach.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="课时费：" style="width: 300px">
        <el-form >
          <el-form-item label="1 课程时：" style="width: 300px">
            <el-input v-model="privateCoursesAddVo.classChange.oneClassHour">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="6 课程时：" style="width: 300px">
            <el-input v-model="privateCoursesAddVo.classChange.sixClassHour">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="10 课程时：" style="width: 300px">
            <el-input v-model="privateCoursesAddVo.classChange.tenClassHour">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-form>

      </el-form-item>
      <el-form-item label="课程备注" style="width: 300px">
        <el-input v-model="privateCoursesAddVo.courses.remarks" placeholder="50字内"/>
      </el-form-item >
      <el-form-item label="课程标签：" style="width: 400px">
        <el-tag
          :key="tag"
          v-for="tag in dynamicTags"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)">
          {{tag}}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标签</el-button>
      </el-form-item>
      <el-form-item label="课程介绍" style="width: 300px">
        <el-input v-model="privateCoursesAddVo.courses.introduce" :rows="5" type="textarea"/>
      </el-form-item >
      <el-form-item label="排序">
        <el-input-number v-model="privateCoursesAddVo.courses.sort" controls-position="right"/>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="handleAddOrEdit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import privateCourses from "../../api/privateCourses";
import coach from "../../api/coach";
  export default {
    data(){
      return {

        saveBtnDisabled: false,    // 主要是为了防止表单重复提交
        imageUrl: '',              // 图片
        coachVo: {},               // 教练对象
        privateCoursesAddVo:{
          courses:{                   // 表单数据绑定的数据模型
            img: "",
            label :'',
          },
          classChange: {            // 课时费对象
            oneClassHour: "",
            sixClassHour: "",
            tenClassHour: ""
          },
        },
        dynamicTags: [],
        inputVisible: false,
        inputValue: ''

      }
    },

    created() {
    this.getCoach();
      // 获取路由地址里面的参数
      console.log(this.$route)
      if(this.$route.params && this.$route.params.id){
        // 表示: 路由参数里面有值，并且有id这个值，就是进行修改操作
        console.log("进行修改操作")
        // 查询课程数据
        this.queryById(this.$route.params.id);
      }
    },

    methods:{
      handleAddOrEdit(){
        // 把saveBtnDisabled 改为true  表示这按钮不可以被点击
        this.saveBtnDisabled = true;
        this.privateCoursesAddVo.courses.label = JSON.stringify(this.dynamicTags);
        console.log("课程数据：",this.privateCoursesAddVo.courses)
        if (this.$route.params && this.$route.params.id){
          //修改
          privateCourses.modifyCourses(this.privateCoursesAddVo).then(res =>{
            console.log("修改课程返回数据：",res)
            if (res.flag){
              this.$message.success("修改成功！")
            }else {
              this.$message.warning("修改失败！")
            }
            // 修改完成，需要跳转到列表页面
            this.$router.push({ path: '/privateCourses' })
          })
        }else {

          privateCourses.addcourse(this.privateCoursesAddVo).then(res =>{
            console.log("添加课程返回数据：",res)
            if (res.flag){
              this.$message.success("添加成功！")
            }else {
              this.$message.warning("添加失败！")
            }
            // 添加完成，需要跳转到列表页面
            this.$router.push({ path: '/privateCourses' })
          })
        }

      },

      //查询教练
      getCoach(){
        coach.queryAll().then(res => {
          console.log("查询教练数据：",res.data);
          this.coachVo = res.data;
        })
      },

      //根据id查询
      queryById(id){
        privateCourses.queryById(id).then(res => {
          console.log("根据id查询的数据：",res);
          this.privateCoursesAddVo = res.data;
          this.dynamicTags = JSON.parse(this.privateCoursesAddVo.courses.label);
        })
      },

      //标签
      handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.dynamicTags.push(inputValue);
          console.log("标签dynamicTags：",this.dynamicTags)
        }
        this.inputVisible = false;
        this.inputValue = '';
      },

      /**
       * 图片上传成功之后回调该函数
       * @param res   响应回来的数据
       * @param file  上传的图片file
       */
      handleAvatarSuccess(res, file) {
        console.log("返回的数据是：",res.data)
        this.privateCoursesAddVo.courses.img = res.data;
      },
      /**
       * 图片上传之前触发该函数，一般用于图片的大小，后缀等信息的校验
       * @param file
       * @returns {boolean}
       */
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

   .el-tag + .el-tag {
     margin-left: 10px;
   }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

</style>
